package com.pmmaster.common.utils;

import com.pmmaster.common.entitis.AdminMenu;
import com.pmmaster.common.entitis.AdminPermission;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: Always_
 * @Date: 2020/2/5
 */
public class TreeUtil {

    /**
     * 菜单树处理
     *
     * @param list
     * @return
     */
    public static AdminMenu handleMenuTree(List<AdminMenu> list) {
        ArrayList<AdminMenu> map = new ArrayList<>();
        if (list.size() > 0) {
            for (AdminMenu menu : list) {
                if (menu.getParentId() == 0) {
                    map = getMenuChild(menu.getParentId(), list);
                }
            }
        }
        return map.get(0);
    }

    /**
     * 权限菜单树
     *
     * @param list
     * @return
     */
    public static AdminPermission handlePermissionTree(List<AdminPermission> list) {
        ArrayList<AdminPermission> map = new ArrayList<>();
        if (list.size() > 0) {
            for (AdminPermission menu : list) {
                if (menu.getParentId() == 0) {
                    map = getPermissionChild(menu.getParentId(), list);
                }
            }
        }
        return map.get(0);
    }

    /**
     * 获取子菜单
     *
     * @param parent_id
     * @param list
     * @return
     */
    private static ArrayList<AdminMenu> getMenuChild(Integer parent_id, List<AdminMenu> list) {
        ArrayList<AdminMenu> map = new ArrayList<>();
        for (AdminMenu menu : list) {
            if (menu.getParentId().equals(parent_id)) {
                menu.setChildren(getMenuChild(menu.getId(), list));
                map.add(menu);
            }
        }
        return map;
    }

    /**
     * 获取子菜单
     *
     * @param parent_id
     * @param list
     * @return
     */
    private static ArrayList<AdminPermission> getPermissionChild(Integer parent_id, List<AdminPermission> list) {
        ArrayList<AdminPermission> map = new ArrayList<>();
        for (AdminPermission menu : list) {
            if (menu.getParentId().equals(parent_id)) {
                menu.setChildren(getPermissionChild(menu.getId(), list));
                map.add(menu);
            }
        }
        return map;
    }
}
